package com.dxp.operation.core;

import com.dxp.operation.vo.respose.base.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author carzy
 */
@RestControllerAdvice
public class OperationResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper mapper = new ObjectMapper();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {
            if (body instanceof Result) {
                OperationLogContextHolder.get().setOut(mapper.writeValueAsString(body));
            } else if (body instanceof String) {
                OperationLogContextHolder.get().setOut((String) body);
            }
        } catch (Exception e) {
            logger.error("read out info err", e);
        }
        return body;
    }
}
